package com.skydroid.h30

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.skydroid.h30.utils.String2ByteArrayUtils
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.IOException
import java.net.*

/**
 * 天空端两路串口
 */
class SkyDataActivity: AppCompatActivity() {
    //天空端 服务IP
    private val serverAddr = "192.168.144.101"
    //TCP端口   14550对应uart0   14551对应uart1
    private val serverPort = 14550
    //超时时间
    private val CONNECTION_TIMEOUT = 20 * 1000
    //socket连接
    private var socket : Socket? = null
    //输出流
    private var mavOut : BufferedOutputStream? = null
    //输入流
    private var mavIn : BufferedInputStream? = null
    //读取线程
    private var mReadThread : ReadThread? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sky_data)
        initView()
    }

    companion object{
        fun start(context: Context){
            context.startActivity(
                Intent(context,
                    SkyDataActivity::class.java)
            )
        }
    }

    private fun initView(){
        findViewById<View>(R.id.btn_open).setOnClickListener {
            openConnect()
        }
        findViewById<View>(R.id.btn_close).setOnClickListener {
            closeConnect()
        }
        findViewById<View>(R.id.btn_send).setOnClickListener {
            sendData()
        }
    }


    /**
     * 创建
     */
    private fun openConnect(){
        Thread{
            try {
                socket =  Socket()
                socket?.connect( InetSocketAddress(serverAddr, serverPort), CONNECTION_TIMEOUT)
                mavOut =  BufferedOutputStream((socket?.getOutputStream()))
                mavIn =  BufferedInputStream(socket?.getInputStream())
            } catch (e: IOException) {
                e.printStackTrace()
            }

            mReadThread = ReadThread()
            mReadThread?.start()
        }.start()
    }

    /**
     * 关闭连接
     */
    private fun closeConnect(){

        //关闭读取线程
        mReadThread?.interrupt()
        mReadThread = null

        try {
            socket?.close()
        }catch (e:IOException){
            e.printStackTrace()
        }
        socket == null

        try {
            mavIn?.close()
        }catch (e:IOException){
            e.printStackTrace()
        }
        mavIn == null


        try {
            mavOut?.close()
        }catch (e:IOException){
            e.printStackTrace()
        }
        mavOut == null

    }

    /**
     * 发送数据
     */
    private fun sendData(){
        Thread{
            var data = "hello uart0".toByteArray()

            mavOut?.write(data)
            mavOut?.flush()
        }.start()
    }

    /**
     * 数据读取线程
     */
    inner class ReadThread:Thread(){
        override fun run() {
            try {
                var buf = ByteArray(1024)
                while (!isInterrupted ){
                    if(mavIn != null){
                        var len = mavIn!!.read(buf)
                        if(len > 0){
                            var tempArray = ByteArray(len)
                            System.arraycopy(buf,0,tempArray,0,len)
                            Log.e("ReadThread","receive：${String2ByteArrayUtils.bytes2Hex(tempArray)}")
                        }
                    }
                }
            }catch (e:InterruptedException){
                e.printStackTrace()
            }catch (e: IOException){
                e.printStackTrace()
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        closeConnect()
    }
}